import Request from 'luch-request';
import { useFansStore } from '@/store/fans';
import { refreshToken } from '@/api/reauth';
import env from '@/config/env';

const fansStore = useFansStore();
const http = new Request({
  baseURL: env.base_url,
  timeout: 8 * 1000,
  header: {
    'Content-Type': 'application/json;charset=utf-8',
  },
});

// 请求拦截
http.interceptors.request.use(
  (config) => {
    config.header = config.header || {};
    if (fansStore.fansinfo.token) {
      config.header.Authorization = 'Bearer ' + fansStore.fansinfo.token;
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

// 是否正在刷新token
let isRefreshing = false;
// 重试请求队列
let requestQueue: any[] = [];

// 响应拦截
http.interceptors.response.use(
  (response) => {
    const code: number = response.data.code;
    if (code == 200) {
      return response.data;
    }

    if (code == 401) {
      if (!isRefreshing) {
        isRefreshing = true;
        return refreshToken()
          .then((res) => {
            requestQueue.forEach(async ({ fn, resolve }) => {
              // 逐个按请求队列顺序重新发起请求
              const res = await fn();
              resolve(res);
            });
            requestQueue = []; // 清空请求队列
            return http.request(response.config);
          })
          .finally(() => {
            isRefreshing = false;
          });
      } else {
        // 同时并发出现的请求 新的token没回来之前 先用promise 存入等待队列中
        return new Promise((resolve) => {
          const fn = () => Promise.resolve(http.request(response.config));
          requestQueue.push({ fn, resolve });
        });
      }
    }

    return Promise.reject(response.data);
  },
  (error) => {
    console.error(error);
    return Promise.reject(error.errMsg);
  }
);

export default http;
